﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Betfairer
{
    public class MarketHelper
    {
        private const char COLON_SPLITTER = ':';
        private const char TILDE_SPLITTER = '~';
        private const char PIPE_SPLITTER = '|';

        private List<Market> _marketData;
        private DateTime _baseDate;

        public MarketHelper()
        {
            _baseDate = new DateTime(1970, 1, 1);
        }

        public static decimal ParseCompletePrices(string prices)
        {
            string[] records = prices.Split(COLON_SPLITTER);

            decimal totalAmountMatched = 0M;
            for (int i = 1; i < records.Length; ++i)
            {
                //Console.WriteLine(s);
                string[] subrecords = records[i].Split(TILDE_SPLITTER);

                totalAmountMatched += Convert.ToDecimal(subrecords[2], CultureInfo.InvariantCulture);
            }

            return totalAmountMatched;
        }

        public List<Market> ParseMarket(string market)
        {
            _marketData = new List<Market>();
            string[] records = market.Split(COLON_SPLITTER);

            foreach (string record in records)
            {
                if (!String.IsNullOrEmpty(record))
                {
                    ParseRecord(record);
                }
            }

            return _marketData;
        }

        private void ParseRecord(string record)
        {
            record = record.Replace(@"~\", @"~").Replace(@"~/", @"~");
            string[] fields = record.Split('~');

            _marketData.Add(new Market
            {
                MarketId = Convert.ToInt32(fields[0]),
                MarketName = fields[1],
                MarketType = fields[2],
                MarketStatus = fields[3],
                EventDateMs = Convert.ToInt64(fields[4]),
                EventDate = _baseDate.AddMilliseconds(Convert.ToDouble(fields[4], CultureInfo.InvariantCulture)), // ToDouble()?!
                MenuPath = fields[5],
                EventHeirachy = fields[6],
                BetDelay = Convert.ToInt32(fields[7]),
                ExchangeId = Convert.ToInt32(fields[8]),
                CountryCode = fields[9],
                LastRefresh = _baseDate.AddMilliseconds(Convert.ToDouble(fields[10], CultureInfo.InvariantCulture)), // ToDouble()?!
                NoOfRunners = Convert.ToInt32(fields[11]),
                NoOfWinners = Convert.ToInt32(fields[12]),
                TotalAmountMatched = Convert.ToDouble(fields[13], CultureInfo.InvariantCulture),
                BspMarket = fields[14] == "Y",
                TurningInPlay = fields[14] == "Y"
            });
        }
    }
}
